package com.yunxi.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.yunxi.common.config.OSSUtil;
import com.yunxi.core.util.GUIDGenerator;
import com.yunxi.core.util.WgrDate;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by admin on 2018/2/24.
 */
@RestController
@RequestMapping("/oss")
@Api(tags = "sys:oss", description = "对象存储验证接口")
public class OSSController {
    private static final Logger log = LoggerFactory.getLogger(OSSController.class);
    @Autowired
    OSSUtil ossUtil;
    @ApiOperation(value = "获取阿里云对象存储鉴权")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subdir", value = "文件夹", required = true, paramType = "body", dataType = "String")
    })
    @PostMapping(value="/getToken")
    public Object getToken(@RequestBody JSONObject object) throws UnsupportedEncodingException {
        return getTokenByDir("/"+object.getString("subdir")+"/");
    }

    @ApiOperation(value = "获取阿里云APP")
    @ApiImplicitParams({
    })
    @PostMapping(value="/getTokenApp")
    public Object getTokenApp() throws UnsupportedEncodingException {
        return getTokenByDir("app"+"/" + WgrDate.getCurrentDateStr2()+"/");
    }

    @ApiOperation(value = "获取阿里云对象存储鉴权")
    @ApiImplicitParams({
    })
    @PostMapping(value="/getTokenUser")
    public Object getTokenUser() throws UnsupportedEncodingException {
        return getTokenByDir("user"+"/" + WgrDate.getCurrentDateStr2()+"/");
    }

    public Object getTokenByDir(String subdir) throws UnsupportedEncodingException {
        String endpoint = ossUtil.ENDPOINT_DOMAIN;
        String dir = "uploadFiles";
        String host = "http://" + ossUtil.BucketName + "." + endpoint;
        OSSClient client = new OSSClient(ossUtil.ENDPOINT, ossUtil.KEY, ossUtil.PASS);
        long expireTime = 60;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        String postPolicy = client.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = postPolicy.getBytes("utf-8");
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = client.calculatePostSignature(postPolicy);
        String savePath = subdir;
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        respMap.put("accessid", ossUtil.KEY);
        respMap.put("OSSAccessKeyId",ossUtil.KEY);
        respMap.put("policy", encodedPolicy);
        respMap.put("signature", postSignature);
        respMap.put("dir", dir);
        respMap.put("host", host);
        respMap.put("expire", String.valueOf(expireEndTime / 1000));
        respMap.put("success_action_status","200");
        String id = GUIDGenerator.getPrimaryKey();
        respMap.put("key", dir+savePath+id);
        respMap.put("tempname", dir+savePath+id);
        respMap.put("bucketName",ossUtil.BucketName);
        return ResponseUtil.ok(respMap);
    }

    @ApiOperation(value = "获取有效下载地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "key", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping(value="/getDownLoadUrl")
    public ApiResult getDownLoadUrl(String key){
        OSSClient client = new OSSClient(ossUtil.ENDPOINT, ossUtil.KEY, ossUtil.PASS);
        long expireTime = 3600;//64800
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        //key转换
        if(key.startsWith("http")){
            key = key.substring(key.indexOf("aliyuncs.com")+13);
        }
        return ResponseUtil.ok(client.generatePresignedUrl(ossUtil.BucketName,key,expiration).toString());
    }

    @PostMapping("/upload")
    @ResponseBody
    //此处用@RequestParam（"xx"）来指定参数名，不加会报错
    public String uploadFiles(@RequestParam("multipartFile") MultipartFile[] multipartfiles) throws IOException {
        OSSUtil ou = new OSSUtil();
        ou.uploadFile("myupload",multipartfiles[0]);
        return "success";
    }
}
